﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace EarringsRecommendationWeb
{
    /// <summary>
    /// Summary description for WSRestFul
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]   
    [System.Web.Script.Services.ScriptService]
    public class WSRestFul : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(UseHttpGet=true,ResponseFormat=ResponseFormat.Json)]
        public void  Add()
        {
            string str = "select short_name, config_name from earringsconfig where short_type ='ERSTY'";
            DataTable dt = SqlClientUtility.ExecuteDataTable(CommandType.Text ,str);
            //int result = num1+num2;
            
            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(dt));
            
        }

        [WebMethod (EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void Validate(string email,string password)
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
            {
                new SqlParameter("@Email", email),
                new SqlParameter ("@Password",password)
            };

            string str = "SELECT Email,MemberName,Address,Telephone,Postcode,Password FROM Member WHERE Email = @Email AND [Password] = @password ";
            //object  value = SqlClientUtility.ExecuteScalar(CommandType.Text, str);

            Member mem = new Member();
            using (SqlDataReader value = SqlClientUtility.ExecuteReader(CommandType.Text, str, sqlParams))
            {
                if (value.Read())
                {
                    mem.Email = SqlClientUtility.GetString(value, "Email", string.Empty);
                    mem.Name = SqlClientUtility.GetString(value, "MemberName", string.Empty);
                    mem.Address = SqlClientUtility.GetString(value, "Address", string.Empty);
                    mem.Telephone = SqlClientUtility.GetString(value,"Telephone", string.Empty);
                    mem.PostCode = SqlClientUtility.GetString(value, "Postcode", string.Empty);
                    mem.Password = SqlClientUtility.GetString(value, "Password", string.Empty); ;
                }
            }           

            Session["member"] = mem;

            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(mem));

        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void Logout(string email, string password)
        {
           
            Session["member"] = null;

            HttpContext.Current.Response.Write("{\"result\": \"success\"}");

        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetPersonalConfig()
        {
            string str = "SELECT Config_Id, Config_TypeTh,Config_Name,Config_NameTh,Config_Image FROM EarringsConfig WHERE config_type in ('Jaw Shape','EarLobe','Ear Shape','Hair Styles','Skin Colors')";
                        
            List<PersonConfig> result = new List<PersonConfig>();            
            using (SqlDataReader value = SqlClientUtility.ExecuteReader(CommandType.Text, str))
            {             
                while (value.Read())
                {
                    string id = Convert.ToString(value["Config_Id"]);
                    string type = Convert.ToString(value["Config_TypeTh"]);
                    string name = Convert.ToString(value["Config_Name"]);
                    string nameTh = Convert.ToString(value["Config_NameTh"]);
                    string imgPath = "Data/PersonalConfig/" + Convert.ToString(value["Config_Image"]);

                    PersonConfig pConfig = new PersonConfig(id, type, name, nameTh, imgPath);
                    result.Add(pConfig);
                }    
            }

            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(result));

        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetRandomEarrings()
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select top 6 er.er_code,er.er_name,er.er_detail");            
            strSql.Append(" ,er.er_price,er.er_image_front,erconf.config_name"); 
            strSql.Append(" from earrings er");
            strSql.Append(" inner join  earringsconfig erconf on er.er_style = erconf.config_id");
            strSql.Append(" order by newid ()");            

            List<EarringsMaster> result = new List<EarringsMaster>();
            using (SqlDataReader value = SqlClientUtility.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (value.Read())
                {
                    string code = Convert.ToString(value["er_code"]);
                    string name = Convert.ToString(value["er_name"]);
                    string detail = Convert.ToString(value["er_detail"]);
                    double price = Convert.ToDouble(value["er_price"]);
                    string imgPath = "Data/Earrings/"+ Convert.ToString(value["config_name"]) + "/" + Convert.ToString(value["er_image_front"]);

                    EarringsMaster pEarrings = new EarringsMaster(code, name, detail, price, imgPath,"","","","");
                    result.Add(pEarrings);

                }
            }

            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(result));

        }

        [WebMethod(EnableSession = true)]
        public string checkSession()
        {
           Member mem = Session["member"] as Member;
            if(mem != null)
            {
                return mem.Email;
            }
            else
            {
                return null;
            }
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetRandomEarringsByStyle(EarringsStyles styles)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select top 6 er.er_code,er.er_name,er.er_detail");
            strSql.Append(" ,er.er_price,er.er_image_front,erconf.config_name");
            strSql.Append(" from earrings er");
            strSql.Append(" inner join  earringsconfig erconf on er.er_style = erconf.config_id");
            strSql.Append(" order by newid ()");

            List<EarringsMaster> result = new List<EarringsMaster>();
            using (SqlDataReader value = SqlClientUtility.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (value.Read())
                {
                    string code = Convert.ToString(value["er_code"]);
                    string name = Convert.ToString(value["er_name"]);
                    string detail = Convert.ToString(value["er_detail"]);
                    double price = Convert.ToDouble(value["er_price"]);
                    string imgPath = "Data/Earrings/" + Convert.ToString(value["config_name"]) + "/" + Convert.ToString(value["er_image_front"]);

                    EarringsMaster pEarrings = new EarringsMaster(code, name, detail, price, imgPath,"","","","");
                    result.Add(pEarrings);

                }
            }

            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(result));

        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetMember(string txtEmail)
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
            {
                new SqlParameter("@Email", txtEmail)
            };

            StringBuilder strSql = new StringBuilder();
            //strSql.Append("DECLARE @Rows int;");
            strSql.Append(" SELECT * FROM Member WHERE Email = @Email") ;

            object value = SqlClientUtility.ExecuteDataTable(CommandType.Text, strSql.ToString(), sqlParams);
        }
        
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void SaveNewMember(string txtEmail, string txtName, string txtAddress, string txtTelephone, string txtPassword, string txtPostCode)
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
            {
                new SqlParameter("@Email", txtEmail),
                new SqlParameter("@Name", txtName),
                new SqlParameter("@Address", txtAddress),
                new SqlParameter("@Telephone", txtTelephone),
                new SqlParameter("@Password", txtPassword)
            };

            StringBuilder strSql = new StringBuilder();
            //strSql.Append("DECLARE @Rows int;");
            strSql.Append(" INSERT INTO Member (Email, MemberName, [Address], Telephone, [Password])");
            strSql.Append(" VALUES ");
            strSql.Append(" ( @Email,@Name, @Address, @Telephone, @Password );");
            strSql.Append(" SELECT @@ROWCOUNT ;	SET NOCOUNT OFF ;");

            object value = SqlClientUtility.ExecuteScalar(CommandType.Text, strSql.ToString(), sqlParams);
                    
            if (value.ToString() == "1")
            {
                HttpContext.Current.Response.Write("{\"result\": \"success\"}");
            }
            else
            {
                HttpContext.Current.Response.Write("{\"result\": \"fail\"}");
            }
            
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void IsDuplicateEmail(string txtEmail)
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
            {
                new SqlParameter("@Email", txtEmail)
            };

            string sqlStr = "SELECT Email FROM MEMBER WHERE Email = @Email";
            object value = SqlClientUtility.ExecuteScalar(CommandType.Text, sqlStr, sqlParams);
            
            if (value == null)
            {
                HttpContext.Current.Response.Write("{\"valid\": \"true\"}");
            }
            else
            {
                HttpContext.Current.Response.Write("{\"valid\": \"false\"}");
            }
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void UpdateMember(string txtEmail, string txtName, string txtAddress, string txtTelephone, string txtPassword, string txtPostCode)
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
            {
                new SqlParameter("@Email", txtEmail),
                new SqlParameter("@Name", txtName),
                new SqlParameter("@Address", txtAddress),
                new SqlParameter("@Telephone", txtTelephone),
                new SqlParameter("@Password", txtPassword),
                new SqlParameter("@Postcode",txtPostCode)
            };

            StringBuilder strSql = new StringBuilder();
            strSql.Append(" UPDATE Member SET MemberName = @Name");
            strSql.Append(" ,[Address]=@Address, Telephone = @Telephone, [Password] = @Password,Postcode=@Postcode");
            strSql.Append(" WHERE Email = @Email;");
            strSql.Append(" SELECT @@ROWCOUNT ;	SET NOCOUNT OFF ;");

            object value = SqlClientUtility.ExecuteScalar(CommandType.Text, strSql.ToString(), sqlParams);

            if (value.ToString() == "1")
            {
                Member mem = Session["member"] as Member;
                mem.Name = txtName;
                mem.Address = txtAddress;
                mem.Telephone = txtTelephone;
                mem.PostCode = txtPostCode;
                mem.Password = txtPassword;

                Session["member"] = mem;

                HttpContext.Current.Response.Write("{\"result\": \"success\"}");
            }
            else
            {
                HttpContext.Current.Response.Write("{\"result\": \"fail\"}");
            }
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void RecalQty(string ERCode, string Qty)
        {
            //string email = string.Empty;
            //email = checkSession();

            RecalQty reQty = new RecalQty(ERCode, Qty);

            if (Session["RecalQty"] == null)
            {                
                List<RecalQty> lstRecalQty = new List<RecalQty>();
                lstRecalQty.Add(reQty);

                Session["RecalQty"] = lstRecalQty;
            }
            else
            {
                List<RecalQty> lstRecalSession= Session["RecalQty"] as List<RecalQty>;
                
                bool toAdd = true;
                foreach (RecalQty item in lstRecalSession)
                {
                    if (item.ERCode == ERCode)
                    {
                        int sumQty = Convert.ToInt32(item.Qty) + Convert.ToInt32(Qty);
                        item.Qty = sumQty.ToString();
                        toAdd = false;
                        break;
                    }
                }
                if (toAdd)
                {
                    lstRecalSession.Add(reQty);
                }

                Session["RecalQty"] = lstRecalSession;
            }
            HttpContext.Current.Response.Write("{\"result\": \"success\"}");
        }
        
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void RecalQtyConfirm(string er_code)
        {
            List<RecalQty> lstRecalSession = Session["RecalQty"] as List<RecalQty>;

            foreach (RecalQty item in lstRecalSession)
            {
                if (item.ERCode == er_code)
                {
                    lstRecalSession.Remove(item);
                    break;
                }
            }

            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(lstRecalSession));
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void ConfirmOrder(string orderdata)
        {
            List<RecalQty> orderconfirm = JsonConvert.DeserializeObject<List<RecalQty>>(orderdata);
            Session["OrderConfirm"] = orderconfirm;
            //Get Receive Date
            string[] returnVal = new string[2];
            returnVal = GlobalFunction.GetReceiveDate(orderconfirm);

            string orderId = string.Empty;

            //Update Remaining, Insert Reserve, ReserveDetail
            if (Session["member"] != null)
            {
                Member mem = Session["member"] as Member;
                orderId = GlobalFunction.UpdateRemaining(orderconfirm, returnVal[1].ToString(),mem);
            }

            Session["OrderId"] = orderId;
            HttpContext.Current.Response.Write("{\"result\": \"success\"}");

            //HttpContext.Current.Response.Write("{\"result\": \"" + orderId + "\"}");

        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetReceiveDate(string data)
        {
            List<RecalQty> orderInBasket = JsonConvert.DeserializeObject<List<RecalQty>>(data);

            string[] returnVal = new string[2];

            returnVal = GlobalFunction.GetReceiveDate(orderInBasket);
            HttpContext.Current.Response.Write("{\"result\": \"" + returnVal[1].ToString() + "\"}");

            //string er_code = string.Empty;
            //string er_codeTmp = string.Empty;
            //string sqlStr = string.Empty;

            //foreach (RecalQty item in orderInBasket)
            //{
            //    if (!string.IsNullOrEmpty(item.ERCode))
            //    {
            //        sqlStr = string.Empty;
            //        sqlStr = "SELECT Er_Remaining FROM Earrings WHERE Er_Code = '" + item.ERCode + "'";

            //        object value = SqlClientUtility.ExecuteScalar(CommandType.Text, sqlStr);

            //        int remain = Convert.ToInt32(value) - Convert.ToInt32(item.Qty);

            //        if (remain <= 0)
            //        {
            //            if (string.IsNullOrEmpty(er_code))
            //            {
            //                er_code += "'" + item.ERCode + "'";
            //            }
            //            else
            //            {
            //                er_code += ",'" + item.ERCode + "'";
            //            }
            //        }
            //    }
            //}

            //string[] returnVal = new string[2];
            //StringBuilder strSql = new StringBuilder();
            //if (!string.IsNullOrEmpty(er_code))
            //{
            //    strSql.Append("SELECT Max(supp.Orderphase)+ 1 AS [NumofDay]");
            //    strSql.Append(" , DATEADD(day, Max(supp.Orderphase)+1,CAST(getdate()AS DATE)) AS [ReceiveDate] FROM Earrings er ");
            //    strSql.Append(" INNER JOIN SupplierOrderphase supp ");
            //    strSql.Append(" ON er.Er_Style = supp.Config_Id");
            //    strSql.Append(" WHERE er.Er_Code IN (").Append(er_code).Append(")");

            //    using (SqlDataReader value = SqlClientUtility.ExecuteReader(CommandType.Text, strSql.ToString()))
            //    {
            //        if (value.Read())
            //        {
            //            returnVal[0] = SqlClientUtility.GetString(value, "NumofDay", string.Empty);
            //            returnVal[1] = SqlClientUtility.GetDateTime(value, "ReceiveDate", DateTime.Now).ToString("dd/MM/yyyy");
            //        }
            //    }
            //    HttpContext.Current.Response.Write("{\"result\": \"" + returnVal[1].ToString() + "\"}");
            //}
            //else
            //{
            //    int day = 1;
            //    DateTime today = DateTime.Now;
            //    DateTime receiveDate = today.AddDays(day);

            //    HttpContext.Current.Response.Write("{\"result\": \"" + receiveDate.ToString("dd/MM/yyyy") + "\"}");
            //}
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void SaveCompareImage(string data)
        {
            List<EarringsCompare> earringsCompare = JsonConvert.DeserializeObject<List<EarringsCompare>>(data);
            string email = string.Empty;
            if (Session["member"] != null)
            {
                Member mem = Session["member"] as Member;
                email = mem.Email;
            }

            //Delete Old date
            string strSql = "DELETE FROM EarringsCompare WHERE Email = '" + email + "'";
            SqlClientUtility.ExecuteNonQuery(CommandType.Text, strSql);

            StringBuilder sqlStr = new StringBuilder();
            foreach (EarringsCompare item in earringsCompare)
            {
                sqlStr = new StringBuilder();
                SqlParameter[] sqlParams = new SqlParameter[] 
                {
                    new SqlParameter("@Email", email),
                    new SqlParameter("@ErCode", item.ERCode),
                    new SqlParameter("@Image", item.ERSampleImage)
                };
                sqlStr.Append("INSERT INTO EarringsCompare (Email, Er_Code, CompareImg)");
                sqlStr.Append(" VALUES ( @Email, @ErCode, @Image )");

                SqlClientUtility.ExecuteNonQuery(CommandType.Text, sqlStr.ToString(),sqlParams);

            }
            HttpContext.Current.Response.Write("{\"result\": \"success\"}");
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetDataEarringsByModel(string er_code,string color_code)
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
            {
                new SqlParameter("@ErCode", er_code),
                new SqlParameter("@ColorCode", color_code)
            };

            StringBuilder sqlStr = new StringBuilder();
            sqlStr.Append("SELECT er.Er_Code, er.Er_Name, er.Er_Price,er.Er_Detail");
            sqlStr.Append(" ,er.Er_Image_Front, er.Er_Image_Side, er.Er_Image_Size, er.Er_Image_Sample");
            sqlStr.Append(" ,erconf.Config_Name, er_Remaining");
            sqlStr.Append(" FROM Earrings er");
            sqlStr.Append(" INNER JOIN EarringsConfig erconf ON er.er_Style = erconf.config_id");
            sqlStr.Append(" INNER JOIN EarringsModel mol ON er.er_code = mol.er_code");            
            sqlStr.Append(" WHERE er.Er_Code IN (");
            sqlStr.Append(" SELECT DISTINCT Er_Code FROM EarringsModel");
            sqlStr.Append(" WHERE ModelName = (SELECT mol.ModelName FROM EarringsModel mol WHERE mol.Er_Code = @ErCode))");
            sqlStr.Append(" AND er.er_color = @ColorCode");

            List<EarringsMaster> result = new List<EarringsMaster>();
            using (SqlDataReader value = SqlClientUtility.ExecuteReader(CommandType.Text, sqlStr.ToString(), sqlParams))
            {
                while (value.Read())
                {
                    string code = Convert.ToString(value["Er_Code"]);
                    string name = Convert.ToString(value["Er_Name"]);
                    string detail = Convert.ToString(value["Er_Detail"]);
                    double price = Convert.ToDouble(value["Er_Price"]);
                    string configName = Convert.ToString(value["Config_Name"]);
                    string imgFront = "Data/Earrings/" + configName + "/" + Convert.ToString(value["Er_Image_Front"]);
                    string imgSide = string.Empty;
                    string imgSize = string.Empty;
                    string imgSample = string.Empty;

                    if (!string.IsNullOrEmpty(Convert.ToString(value["Er_Image_Side"])))
                    {
                        imgSide = "Data/Earrings/" + configName + "/" + Convert.ToString(value["Er_Image_Side"]);
                    }
                    if (!string.IsNullOrEmpty(Convert.ToString(value["Er_Image_Size"])))
                    {
                        imgSize = "Data/Earrings/" + configName + "/" + Convert.ToString(value["Er_Image_Size"]);
                    }
                    if (!string.IsNullOrEmpty(Convert.ToString(value["Er_Image_Sample"])))
                    {
                        imgSample = "Data/Earrings/" + configName + "/" + Convert.ToString(value["Er_Image_Sample"]);
                    }
                    //Check Remaining
                    string status = string.Empty;
                    if (Convert.ToInt32(value["er_Remaining"]) <= 0)
                    {
                        status = GlobalValue.ERSTATUS_WAIT;
                    }
                    else
                    {
                        status = GlobalValue.ERSTATUS_READY;
                    }

                    EarringsMaster pEarrings = new EarringsMaster(code, name, detail, price, imgFront, imgSide, imgSize, imgSample, status);
                    result.Add(pEarrings);
                }
            }

            HttpContext.Current.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
}
